package org.huatek.anders.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.huatek.anders.entity.OpenUserEntity;
import org.huatek.anders.service.Oauth2Service;
import org.huatek.anders.utils.R;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;


/**
 * @author anders
 * @date 2018-12-03 09:27
 **/
@Slf4j
@RestController
@RequestMapping("${common.api.url}/${common.api.version}/oauth2")
public class Oauth2Controller extends BaseController {
    @Reference
    private Oauth2Service oauth2Service;

    @PostConstruct
    public void init() {
        // 检查服务是否成功发现服务
        log.info("【Dubbo服务oauth2Service注入检测】:" + oauth2Service);
    }

    private OpenUserEntity initUserEntity(HttpServletRequest request, String code, String openId) {
        OpenUserEntity openUserEntity = (OpenUserEntity) request.getAttribute("loginUser");
        if (openUserEntity == null) {
            openUserEntity = new OpenUserEntity();
        }
        openUserEntity.setCode(code);
        openUserEntity.setOpenid(openId);
        return openUserEntity;
    }

    /**
     * 普通账号登陆
     * @param openUserEntity 用户名、密码
     * @return R
     */
    @PostMapping("/account/login")
    public R loginByAccount(OpenUserEntity openUserEntity) {
        boolean empty = StringUtils.isEmpty(openUserEntity) || StringUtils.isEmpty(openUserEntity.getPassword()) || (StringUtils.isEmpty(openUserEntity.getMobile()) && StringUtils.isEmpty(openUserEntity.getUserName()));
        if (empty) {
            return R.error("用户名或密码为空");
        }
        return oauth2Service.loginByAccount(openUserEntity);
    }

    /**
     * qq回掉地址
     *
     * @param code   qq回掉返回code
     * @param openId 已登陆后前端存储openId，手动调用传入openId获取token，不传则为首次qq回掉
     * @return R
     */
    @GetMapping("/qq/login")
    public R loginByQq(HttpServletRequest request, @RequestParam("code") String code, @RequestParam("openId") String openId) {
        return oauth2Service.loginByQq(initUserEntity(request, code, openId));
    }

    @GetMapping("/wechat/login")
    public R loginByWechat(HttpServletRequest request, @RequestParam("code") String code, @RequestParam("openId") String openId) {
        return oauth2Service.loginByWechat(initUserEntity(request, code, openId));
    }

    @GetMapping("/account/logout")
    public R logoutUser(HttpServletRequest request){
        OpenUserEntity openUserEntity = (OpenUserEntity) request.getAttribute("loginUser");
        return oauth2Service.logoutUser(openUserEntity);
    }

    @GetMapping("/main")
    public R main() {
        return R.ok("进来了");
    }
}
